﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using StudentInformation_Demo.Models;
using StudentInformation_Demo.ModelViews;
using StudentInformation_Demo.Services.Interface;

namespace StudentInformation_Demo.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        private readonly IStudentServices services;
        private readonly IWebHostEnvironment webHostEnvironment;

        public HomeController(
            IStudentServices services,
            IWebHostEnvironment webHostEnvironment)
        {
            this.services = services;
            this.webHostEnvironment = webHostEnvironment;
        }

        public IActionResult Index([FromQuery]PageEntity pageEntity)
        {
            var list = services.GetAllStudent(pageEntity);
            ViewBag.page = pageEntity;
            ViewBag.Previous = pageEntity.HasPrevious;
            ViewBag.Next = pageEntity.HasNext;
            return View(list);
        }

        public IActionResult GetStudent(int Id)
        {
            var model = services.GetStudent(Id);
            var major = services.GetMajor(model.MId);
            ViewData["MajorName"] = major.MojorName;
            if (model == null)
            {
                return View("NotFound");
            }
            return View(model);
        }

        [HttpGet]
        public IActionResult UpdateStudent(int Id)
        {
            var majors = services.GetAllMajors();
            List<SelectListItem> items = new List<SelectListItem>();
            foreach (var major in majors)
            {
                items.Add(new SelectListItem
                {
                    Value = major.Id.ToString(),
                    Text = major.MojorName
                });
            }
            ViewBag.SelectItem = items;
            var model = services.GetStudent(Id);
            if (model == null)
            {
                return View("NotFound");
            }
            StudentViewModels m = new StudentViewModels
            {
                Birthday = model.Birthday,
                MId = model.MId,
                Email = model.Email,
                Gender = model.Gender,
                SNo = model.SNo,
                Name = model.Name,
                TelPhone = model.TelPhone,
                Id = model.Id
            };
            ViewBag.imgPath = model.ImgPath;
            return View(m);
        }
        [HttpPost]
        public IActionResult UpdateStudent(StudentViewModels student)
        {
            if (ModelState.IsValid)
            {
                //用于获取Guid的然后添加到传入的文件以便防止上传的图片名称一致
                string uniqueFileName = null;
                //用于存放服务器中文件路径  然后存入数据库
                string filePath = null;
                if (student.ImgFile != null)
                {
                    //获取wwwroot路径下的imges文件夹路径
                    string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "imges");
                    uniqueFileName = Guid.NewGuid().ToString() + "_" + student.ImgFile.FileName;
                    //将wwwroot/imges + 添加了Guid的文件结合起来 成为这个文件在服务器中的路径 然后存入到数据库中
                    filePath = Path.Combine(uploadsFolder, uniqueFileName);
                    //将从前端获得的文件复制到filePath的路径并使用创建方式
                    student.ImgFile.CopyTo(new FileStream(filePath, FileMode.Create));
                }
                else
                {
                    var s = services.GetStudent(student.Id);
                    uniqueFileName = s.ImgPath;
                }
                Student model = new Student
                {
                    SNo = student.SNo,
                    Birthday = student.Birthday,
                    MId = student.MId,
                    Email = student.Email,
                    Gender = student.Gender,
                    Id = student.Id,
                    Name = student.Name,
                    TelPhone = student.TelPhone,
                    ImgPath = uniqueFileName
                };
                services.UpdateStudent(model);
                services.Save();
                return RedirectToAction("Index");
            }
            ModelState.AddModelError("", "错误");
            return View();
        }

        [HttpGet]
        public IActionResult CreateStudent()
        {
            var model = services.GetAllMajors();
            List<SelectListItem> items = new List<SelectListItem>();
            foreach (var m in model)
            {
                items.Add(new SelectListItem
                {
                    Value = m.Id.ToString(),
                    Text = m.MojorName
                });
            }
            ViewBag.SelectItem = items;
            return View();
        }
        [HttpPost]
        public IActionResult CreateStudent(StudentViewModels student)
        {
            if (student.Name == null)
            {
                ModelState.AddModelError("", "错误");
                //如果Name值为空时在前端返回错误并给专业的选项添加item选项
                List<SelectListItem> items = new List<SelectListItem>();
                var model = services.GetAllMajors();
                foreach (var m in model)
                {
                    items.Add(new SelectListItem
                    {
                        Value = m.Id.ToString(),
                        Text = m.MojorName
                    });
                }
                ViewBag.SelectItem = items;
                return View();
            }
                //用于获取Guid的然后添加到传入的文件以便防止上传的图片名称一致
                string uniqueFileName = null;
                //用于存放服务器中文件路径  然后存入数据库
                string filePath = null;
                if (student.ImgFile != null)
                {
                    //获取wwwroot路径下的imges文件夹路径
                    string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "imges");
                    uniqueFileName = Guid.NewGuid().ToString() + "_" + student.ImgFile.FileName;
                    //将wwwroot/imges + 添加了Guid的文件结合起来 成为这个文件在服务器中的路径 然后存入到数据库中
                    filePath = Path.Combine(uploadsFolder, uniqueFileName);
                    //将从前端获得的文件复制到filePath的路径并使用创建方式
                    student.ImgFile.CopyTo(new FileStream(filePath, FileMode.Create));
                }
                Student s = new Student
                {
                    SNo = student.SNo,
                    Birthday = student.Birthday,
                    MId = student.MId,
                    Name = student.Name,
                    Email = student.Email,
                    Gender = student.Gender,
                    Id = student.Id,
                    TelPhone = student.TelPhone,
                    ImgPath = uniqueFileName
                };

                services.AddStudent(s);
                services.Save();
                return RedirectToAction("Index");
        }

        public IActionResult DeleteStudent(int Id)
        {
            var model = services.GetStudent(Id);
            if (model != null)
            {
                services.DeleteStudent(Id);
                services.Save();
            }
            return RedirectToAction("index");
        }
        [HttpGet]
        public IActionResult SelectStudent(PageEntity pageEntity)
        {
            ViewBag.page = pageEntity;
            ViewBag.Previous = pageEntity.HasPrevious;
            ViewBag.Next = pageEntity.HasNext;
            List<Student> students = new List<Student>();
            return View(students);
        }
        [HttpPost]
        public IActionResult SelectStudent(string queryStr, PageEntity pageEntity)
        {
            if (queryStr == null)
            {
                var s = services.GetAllStudent(null);
                return View(s);
            }
            else
            {
                var s = services.SelectStudent(queryStr);
                if (s == null)
                {
                    return View("NotFound");
                }
                return View(s);
            }

        }

        [HttpGet]
        public IActionResult AddMajor()
        {
            return View();
        }

        [HttpPost]
        public IActionResult AddMajor(Major major)
        {
            services.AddMajor(major);
            services.Save();
            return RedirectToAction("index");
        }
    }
}
